import axios from "axios";
import {message} from "ant-design-vue";


let count = 0;

function parseJSON(response) {
    count--
    if (count === 0) {
        const globalLoadingStyle = document.getElementById('global_loading').style;
        globalLoadingStyle.background = 'rgba(0, 0, 0, 0)';
        globalLoadingStyle.transition = 'all 1s ease 0s';
        globalLoadingStyle.visibility = 'hidden';
    }
    return response
}

export const request = (options) => {
    const globalLoadingStyle = document.getElementById('global_loading').style;
    globalLoadingStyle.background = 'rgba(0, 0, 0, 0.3)';
    globalLoadingStyle.transition = 'all 1s ease 0s';
    globalLoadingStyle.visibility = 'visible';
    count++;
    const defaultRequestOption = {
        method: options.method || "GET",
        url: options.url || '',
        pureData: true,
        data: {},
        params: {},
    }
    const headers = {'token': localStorage.getItem('token') || '', 'clientType': 'Web'};
    options = Object.assign(defaultRequestOption, options);
    axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API : process.env.VUE_APP_BASE_URL;
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    return axios.request({
        url: options.url,
        method: options.method,
        headers,
        data: options.data,
        params: options.params,
    })
        .then(parseJSON)
        .then(res => {
            const getData = res.data;
            if (getData.code === 500) {
                message.warn("登录已过期，请重新登录");
                return;
            }
            if (options.pureData) {
                return getData.data;
            } else {
                return res.data;
            }
        }).catch(err => {
            count--;
            if (count === 0) {
                const globalLoadingStyle = document.getElementById('global_loading').style;
                globalLoadingStyle.background = 'rgba(0, 0, 0, 0)';
                globalLoadingStyle.transition = 'all 1s ease 0s';
                globalLoadingStyle.visibility = 'hidden';
            }

            message.destroy();
            message.error('请求错误。')
        });
}